package cn.gyxy.service.realm;


import cn.gyxy.mapper.GuanliMapper;
import cn.gyxy.pojo.Guanli;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class ShiroRealm extends AuthorizingRealm {
    @Autowired
    private GuanliMapper guanliMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        Guanli guanli = (Guanli) principalCollection.getPrimaryPrincipal();
//        if (guanli.getPermission().equals(0))
//            throw new IllegalArgumentException("无操作权限");
        //2.基于登录用户id获取用户权限标识,是否是管理员
        Set<String> stringPermissions =
                guanliMapper.findUserPermissions(guanli.getId());
//        if(stringPermissions.equals(0)) throw new AuthorizationException();
        //3.封装数据并返回
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(stringPermissions);
        return info;
//        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)  {

        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
        String username = upToken.getUsername();
        //2.基于用户名查询从数据库用户信息
        Guanli guanli = guanliMapper.chaxunGuanlixinxi(username);
        System.out.println("数据库查询用户信息"+guanli);
        //3.判断用户是否存在
        if (guanli == null) throw new UnknownAccountException();//账户不存在

        SimpleAuthenticationInfo info =
                new SimpleAuthenticationInfo(
                        guanli, //principal 传入的用户身份
                        guanli.getPassword(),//hashedCredentials
                        getName());
        return info;
//        return null;
    }
}
